package com.pine.app.module.security.oauth.provider;


import com.pine.app.module.security.core.Authentication;
import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.oauth.exception.AuthenticationException;
import com.pine.app.module.security.oauth.provider.token.AccessTokenService;
import com.pine.app.module.security.oauth.provider.token.OAuth2AccessToken;
import com.pine.app.module.security.oauth.support.HttpTokenRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 *  身份校验实现类
 * @author xiaoyuan
 * @create 2019/10/9 15:28
 **/
public class OAuthAuthenticationManager implements AuthenticationManager {

    private AccessTokenService accessTokenService;

    @Autowired
    public void setAccessTokenService(AccessTokenService accessTokenService) {
        this.accessTokenService = accessTokenService;
    }

    @Override
    public OAuth2AccessToken accessToken(Authentication authentication) {
        if (authentication == null) {
            ErrorType.ACCESS_DENIED.throwThis(AuthenticationException::new);
        }
        return new DefaultOauth2TokenBuilder().getAccessToken((OAuth2Authentication) authentication);
    }

    @Override
    public OAuth2Authentication authentication(Authentication authentication) {
        if(authentication==null){
            ErrorType.ACCESS_DENIED.throwThis(AuthenticationException::new);
        }
        return authentication((String) authentication.getPrincipal());
    }

    @Override
    public OAuth2Authentication authentication(String access_token) {
        if(StringUtils.isBlank(access_token)){
            ErrorType.ACCESS_DENIED.throwThis(AuthenticationException::new);
        }
        OAuth2Authentication oAuth2Authentication =  accessTokenService.loadAuthentication(access_token);
        if(oAuth2Authentication==null){
            ErrorType.EXPIRED_TOKEN.throwThis(AuthenticationException::new);
        }
        return oAuth2Authentication;
    }
}
